import express from 'express';
import path from 'path';
import cors from 'cors';
import { fileURLToPath } from 'url';
import { config } from './config.js';
import { buildSignatureForUrl } from './wechat.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
app.use(cors());
app.use(express.json());

// Serve static frontend
const publicDir = path.join(__dirname, '../public');
app.use(express.static(publicDir));

app.get('/health', (req, res) => {
  res.json({ status: 'ok', time: new Date().toISOString() });
});

app.get('/api/wechat-signature', async (req, res, next) => {
  try {
    const url = req.query.url;
    const data = await buildSignatureForUrl(url, config.appId, config.appSecret);
    res.json({ success: true, data });
  } catch (err) {
    next(err);
  }
});

// Global error handler
app.use((err, req, res, next) => {
  console.error('[Error]', err?.message || err, err?.stack);
  const status = 500;
  const detail = err?.response?.data || undefined;
  res.status(status).json({ success: false, error: err?.message || 'Internal Error', detail });
});

const port = config.port;
app.listen(port, () => {
  console.log(`Server started on http://localhost:${port}`);
});